package com.wlz.java8.lambda.paralle;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @author： wlz
 * @Date 2020/7/6 10:17
 * @description： TODO
 * @version: 1.0
 *
 *  并行流和串行流
 */
public class StreamApi2 {

    public static long CONSTANT = 10000000000L;

    /**
     * 需求:计算0到1亿的和
     */
    @Test
    public void test() {
        Instant start = Instant.now();
        long sum = 0L;
        for (long i = 0; i < CONSTANT; i++) {
            sum += i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为: " + Duration.between(start, end).toMillis());
    }

    @Test
    public void test2() {
        Instant start = Instant.now();
        ForkJoinPool fjp = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinCalculate( 0 , CONSTANT );
        Long sum = fjp.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println( "耗费时间为。"+Duration.between(start, end). toMillis());
    }

    @Test
    public void test3() {
        Instant start = Instant . now();
        long res = LongStream.rangeClosed(0, CONSTANT).
                parallel().reduce(0,Long::sum) ;
        System.out.println(res);
        Instant end = Instant.now();
        System.out.println( "耗费时间为: "+Duration. between(start, end). toMillis());
    }

}
